// run: $exec < input
#include <iostream>
#include <stack>
#include <list>

struct command
{
	bool c; // false: col  true: row
	int x, y, rank;
};

int const maxn = 107;
int initial[maxn][maxn], dest[maxn][maxn];
int n, m;

std::list<command> cmd;
typedef std::list<command>::iterator cmd_iter;

bool check(command const & a)
{
	if (a.c) {
		for (int i = 0; i < n; i++)
			if (!(dest[a.x][i] == a.y || !dest[a.x][i])) return false;
	} else {
		for (int i = 0; i < n; i++)
			if (!(dest[i][a.x] == a.y || !dest[i][a.x])) return false;
	}

	if (a.c) {
		for (int i = 0; i < n; i++)
			dest[a.x][i] = 0;
	} else {
		for (int i = 0; i < n; i++)
			dest[i][a.x] = 0;
	}
	return true;
}

int main()
{
	std::ios::sync_with_stdio(false);
	int T; std::cin >> T;
	while (T--) {
		cmd.clear();
		std::cin >> n >> m;
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++) std::cin >> initial[i][j];
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++) std::cin >> dest[i][j];
		for (int i = 0; i < m; i++) {
			command cc;
			char ch; std::cin >> ch >> cc.x >> cc.y;
			cc.x--;
			cc.c = ch == 'H'; cc.rank = i + 1;
			cmd.push_back(cc);
		}

		std::stack<int> ans;

		while (!cmd.empty()) {
			for (cmd_iter it = cmd.begin(); it != cmd.end(); ++it) {
				if (check(*it)) {
					ans.push((*it).rank);
					cmd.erase(it);
					break;
				}
			}
		}

		std::cout << ans.top(); ans.pop();
		for (; !ans.empty(); ans.pop()) std::cout << ' ' << ans.top();
		std::cout << '\n';
	}
}

